/**
 * Created by Administrator on 2017/7/11.
 */

let variable = require('../data/variable.js');
let bluedSDK = require('../util/bluedSDK.js');
let publicDao = require('../mysql/publicDao.js');
let packageDao = require('../mysql/packageDao.js');
let userDao = require('../mysql/userDao.js');
let taskDao = require('../mysql/taskDao.js');
let timesDao = require('../mysql/timesDao.js');
let util = require('../util/util.js');
let mem = require('../util/mem.js');
let msg = require('../util/msg.js');
let gameData = require('../util/gameData.js');
let log = require('../util/log.js');

let call = module.exports;

call.socket = {
    setUuid: function (userId, uuid) {
        if (!mem.sockets[userId]) {
            mem.sockets[userId] = {};
        }
        mem.sockets[userId].uuid = uuid;
        return true;
    },
    getUuid: function (userId) {
        if (!mem.sockets[userId]) {
            return false;
        }
        return mem.sockets[userId].uuid;
    },
    setCid: function (userId, cid) {
        if (!mem.sockets[userId]) {
            mem.sockets[userId] = {};
        }
        mem.sockets[userId].cid = cid;
        return true;
    },
    getCid: function (userId) {
        if (!mem.sockets[userId]) {
            return false;
        }
        return mem.sockets[userId].cid;
    },
    setBluedId: function (userId, bluedId) {
        if (!mem.sockets[userId]) {
            mem.sockets[userId] = {};
        }
        mem.sockets[userId].bluedId = bluedId;
        return true;
    },
    getBluedId: function (userId) {
        if (!mem.sockets[userId]) {
            return false;
        }
        return mem.sockets[userId].bluedId;
    },
    clear: function (userId) {
        if (!mem.sockets[userId]) {
            return false;
        }
        call.weixin.clear(mem.sockets[userId].weixinId);
        call.blued.clear(mem.sockets[userId].bluedId);
        delete mem.sockets[userId];
    },
    setWeixinId: function (userId, weixinId) {
        if (!mem.sockets[userId]) {
            mem.sockets[userId] = {};
        }
        console.log("设置微信ID",userId,weixinId);
        mem.sockets[userId].weixinId = weixinId;
        return true;
    },
    getWeixinId: function (userId) { 
        if (!mem.sockets[userId]) {
            return false;
        }   
        var weixinId = mem.sockets[userId].weixinId;
        console.log("获取微信ID",userId,weixinId);
        return weixinId;
    }   
};
call.robot = {
    check: function (lv) {
        if (!gameData.d.config.robotTurnOn) {
            return false;
        }
        if (!mem.robots[lv]){
            return false;
        }
        if (Object.keys(mem.robots[lv]).length < 2) {
            return false;
        }
        return true;
    },
    apply: function (lv, cb) {
        mem.robotApply.push({'lv': lv, 'cb': cb});
    },
    checkGold: function (lv, gold) {
        if (gold < gameData.d.gameLv[lv].minCoin) {
            return false;
        }
        if (gameData.d.gameLv[lv].maxCoin != -1 && gold > gameData.d.gameLv[lv].maxCoin) {
            return false;
        }
        return true;
    }
};
call.blued = {
    setAccessToken: function (uid, accessToken, expire) {
        if (!mem.blueds[uid]) {
            mem.blueds[uid] = {};
        }
        mem.blueds[uid].accessToken = accessToken;
        mem.blueds[uid].expire = (Date.now() + (expire * 1000));
        return true;
    },
    getAccessToken: function (uid) {
        if (!mem.blueds[uid]) {
            return false;
        }
        return mem.blueds[uid].accessToken;
    },
    setPlatform: function (uid, platform) {
        if (!mem.blueds[uid]) {
            mem.blueds[uid] = {};
        }
        mem.blueds[uid].platform = platform;
        return true;
    },
    getPlatform: function (uid) {
        if (!mem.blueds[uid]) {
            return false;
        }
        return mem.blueds[uid].platform;
    },
    putBluedStatus: function (userId, status) {
        if (!mem.sockets[userId]) {
            return false;
        }
        if (!call.socket.getBluedId(userId)) {
            return false;
        }
        if (!mem.blueds[call.socket.getBluedId(userId)]) {
            return false;
        }
        bluedSDK.status(mem.blueds[call.socket.getBluedId(userId)].accessToken, status, function (result) {
            console.log('bluedSDK.status', result);
        });
    },
    clear: function (uid) {
        if (!mem.blueds[uid]) {
            return false;
        }
        delete mem.blueds[uid];
    },
};
call.weixin = {
    setAccessToken: function (uid, accessToken, expire ,refreshToken) {
        if (!mem.weixins[uid]) {
            mem.weixins[uid] = {};
        }
        console.log("setAccessToken>",uid,accessToken);
        mem.weixins[uid].accessToken = accessToken;
        mem.weixins[uid].expire = (Date.now() + (expire * 1000));
        mem.weixins[uid].refreshToken = refreshToken;
        return true;
    },  
    getRefreshToken: function (uid) {
        if (!mem.weixins[uid]) {
            return false;
        }
        return mem.weixins[uid].refreshToken;
    },
    getAccessToken: function (uid) {
        console.log("getAccessToken>",uid);
        if (!mem.weixins[uid]) {
            return false;
        }
        console.log("AccessToken>",mem.weixins[uid].accessToken);
        return mem.weixins[uid].accessToken;
    },
    setPlatform: function (uid, platform) {
        if (!mem.weixins[uid]) {
            mem.weixins[uid] = {};
        }
        mem.weixins[uid].platform = platform;
        return true;
    },
    getPlatform: function (uid) {
        if (!mem.weixins[uid]) {
            return false;
        }
        return mem.weixins[uid].platform;
    },  
    setTicket: function (uid, ticket, expire) {
        if (!mem.weixins[uid]) {
            mem.weixins[uid] = {};
        }   
        console.log("setTicket>",uid,ticket);
        mem.weixins[uid].ticket = ticket;
        mem.weixins[uid].ticket_expire = expire;
        return true;
    },  
    getTicket: function (uid) {
        console.log("getTicket>",uid);
        if (!mem.weixins[uid]) {
            return false;
        }   
        console.log("ticket>",mem.weixins[uid].ticket);
        return mem.weixins[uid].ticket;
    },  
    putWeixinStatus: function (userId, status) {
        if (!mem.sockets[userId]) {
            return false;
        }
        if (!call.socket.getWeixinId(userId)) {
            return false;
        }   
        if (!mem.weixins[call.socket.getWeixinId(userId)]) {
            return false;
        }  
        /*** 
        weixinSDK.status(mem.weixins[call.socket.getWeixinId(userId)].accessToken, status, function (result) {
        });
        ***/
    },
    clear: function (uid) {
        if (!mem.weixins[uid]) {
            return false;
        }   
        delete mem.weixins[uid];
    },
};
call.gameLists = {
    amount: function () {
        let data = {};
        for (let i in gameData.d.gameLv) {
            data[i] = 0;
        }
        for (let i in mem.gameLists) {
            data[mem.gameLists[i].lv] += 3;
        }
        return data;
    },
    getGames: function () {
        return mem.gameLists;
    },
    addGame: function (data) {
        let gameId = data.gameId;
        mem.gameLists[gameId] = {};
        mem.gameLists[gameId].serverId = data.serverId;
        mem.gameLists[gameId].lv = data.lv;
        mem.gameLists[gameId].createTime = data.createTime;
    },
    delGame: function (gameId) {
        if (!mem.gameLists[gameId]) {
            return false;
        }
        delete mem.gameLists[gameId];
    },
    updateGame: function (data) {
        if (!data.gameId) {
            return false;
        }
        if (!mem.gameLists[data.gameId]) {
            return false;
        }
        let gameId = data.gameId;
        mem.gameLists[gameId].multiple = data.multiple;
        mem.gameLists[gameId].playerId = data.playerId;
        mem.gameLists[gameId].playerName = data.playerName;
    },
    syncGame: function (data) {
        console.log(data);
        let games = [];
        for (let gameId in mem.gameLists) {
            if (mem.gameLists[gameId].serverId != data.serverId) {
                continue;
            }
            games.push(gameId);
        }
        for (let id in games) {
            if (data.gameIds.indexOf(games[id]) < 0) {
                call.gameLists.delGame(games[id]);
                call.gameLists.delRecruit(games[id]);
                log.p('sync game kill ' + games[id]);
            }
        }
    },
    killGame: function (data) {
        //if (mem.gameLists[data.id].serverId) {
        //    console.log()
        //    for (let i in mem.clients) {
        //        if (mem.clients[i].serverId != mem.gameLists[data.id].serverId) {
        //            continue;
        //        }
        //        console.log(i)
        //        msg.send(i, 1, 'gameKill', {'id': data.id});
        //    }
        //}
        call.gameLists.delGame(data.id);
        call.gameLists.delRecruit(data.id);
        log.p('gm kill game ' + data.id);
    },
    updateGamePraise: function (data) {
        let endTime = Date.now() + (60 * 1000);
        let playmate = {};
        for (let i = 0; i < 3; i++) {
            playmate[data[i].id] = !!data[i].isRobot;
        }
        let playmateJson = JSON.stringify(playmate);
        playmate = null;
        for (let i in data) {
            if (data[i].isRobot) {
                continue;
            }
            mem.gamePraisePlayers[data[i].id] = {
                'endTime': endTime,
                'local': i,
                'name': data[i].name,
                'playmate': JSON.parse(playmateJson),
                'task': data[i].task
            };
        }
    },
    setGamePraise: function (data) {
        if (!mem.gamePraisePlayers[data.userId]) {
            return false;
        }
        if (data.userId == data.target) {
            return false;
        }
        if (mem.gamePraisePlayers[data.userId].playmate[data.target] === true) {
            return false;
        }
        if (mem.gamePraisePlayers[data.userId].playmate[data.target] === undefined) {
            return false;
        }
        mem.gamePraisePlayers[data.userId].playmate[data.target] = true;
        msg.send(call.socket.getCid(data.target), call.socket.getUuid(data.target), 'gamePraise', {
            'userId': data.userId,
            'name': mem.gamePraisePlayers[data.userId].name
        });
        let userModel = new userDao();
        userModel.inId(data.target, function (err, res) {
            userModel.add('praise', 1);
            userModel.save(function () {
            });
        });
    },
    addRecruit: function (data) {
        let gameId = data.gameId;
        mem.recruits[gameId] = {};
        mem.recruits[gameId].masterId = data.id;
        mem.recruits[gameId].masterName = data.name;
        mem.recruits[gameId].masterHead = data.avatar ? data.avatar : null;
        mem.recruits[gameId].bluedId = data.bluedId ? data.bluedId : null;
    },
    delRecruit: function (gameId) {
        if (!mem.recruits[gameId]) {
            return false;
        }
        delete mem.recruits[gameId];
    },
    getRecruit: function (bluedId, cb) {
        if (gameData.d.config.customNeedFriend == 1) {
            call.gameLists.getRecruitFriend(bluedId, cb);
        } else {
            call.gameLists.getRecruitAll(bluedId, cb);
        }
    },
    getRecruitAll: function (bluedId, cb) {
        let games = [];
        for (let i in mem.recruits) {
            let game = mem.recruits[i];
            let data = {};
            data.gameId = i;
            data.mode = 1;
            data.masterId = game.masterId;
            data.masterName = game.masterName;
            data.masterHead = game.masterHead;
            games.push(data);
        }
        cb(games);
    },
    getRecruitFriend: function (bluedId, cb) {
        let accessToken = call.blued.getAccessToken(bluedId);
        bluedSDK.friends(accessToken, bluedId, function (res3) {
            if (res3.code != 200) {
                cb([]);
                return false;
            }
            let friendUid = [];
            if (res3.data) {
                for (let i in res3.data) {
                    friendUid.push(res3.data[i].uid);
                }
            }
            let games = [];
            if (friendUid.length > 0) {
                for (let i in mem.recruits) {
                    let game = mem.recruits[i];
                    if (friendUid.indexOf(game.bluedId) < 0) {
                        continue;
                    }
                    let data = {};
                    data.gameId = i;
                    data.mode = 1;
                    data.masterId = game.masterId;
                    data.masterName = game.masterName;
                    data.masterHead = game.masterHead;
                    games.push(data);
                }
            }
            cb(games);
        });
    }
};
call.package = {
    addItem: function (userId, itemAddId, cb) {
        let time = util.timeStamp();
        let packageModel = new packageDao();
        packageModel.inItemId(userId, gameData.d.itemAdd[itemAddId].itemId, function (err, res) {
            if (res) {
                if (packageModel.data.expiredTime == -1) {
                    return false;
                }
                let expiredTime = -1;
                if (gameData.d.itemAdd[itemAddId].time >= 0) {
                    expiredTime = packageModel.data.expiredTime;
                    if (expiredTime < time) {
                        expiredTime = time;
                    }
                    expiredTime += gameData.d.itemAdd[itemAddId].time;
                }
                packageModel.set('expiredTime', expiredTime);
                packageModel.save(function (err, res) {
                    cb(util.itemInfo(packageModel.data));
                    return true;
                });
                return false;
            }
            let expiredTime = -1;
            if (gameData.d.itemAdd[itemAddId].time >= 0) {
                expiredTime = util.timeStamp() + gameData.d.itemAdd[itemAddId].time;
            }
            packageModel.set('userId', userId);
            packageModel.set('itemId', gameData.d.itemAdd[itemAddId].itemId);
            packageModel.set('expiredTime', expiredTime);
            packageModel.save(function (err, res) {
                let data = {};
                data.id = res.res.insertId;
                data.userId = userId;
                data.itemId = gameData.d.itemAdd[itemAddId].itemId;
                data.expiredTime = expiredTime;
                cb(util.itemInfo(data));
            });
        });
    }
};
call.task = {
    list: function (userId, cb) {
        publicDao.init().table('task').pluck('taskId', 'num', 'finish').wheres('userId', '=', userId).get(function (err, res) {
            if (err !== null) {
                return false;
            } else if (res.length == 0) {
                return false;
            } else {
                let data = {};
                for (let i in res) {
                    data[res[i].taskId] = {'num': res[i].num, 'finish': res[i].finish};
                }
                cb(data);
            }
        });
    },
    update2: function (userId, taskId, num) {
        let taskModel = new taskDao();
        taskModel.inTaskId(userId, taskId, function (err, res) {
            if (err || !res) {
                return false;
            }
            taskModel.set('num', num);
            taskModel.save(function () {
            });
        });
    },
    finish2: function (userId, taskId, cb) {
        let taskModel = new taskDao();
        taskModel.inTaskId(userId, taskId, function (err, res) {
            if (err || !res) {
                cb(1);
                return false;
            }
            if (res.res.num < gameData.d.task[taskId].num) {
                cb(2);
                return false;
            }
            if (res.res.finish == 1) {
                cb(5);
                return false;
            }
            let userModel = new userDao();
            userModel.inId(userId, function (err1, res1) {
                if (res1 == null) {
                    cb(3);
                    return false;
                }
                let coinType = gameData.d.task[taskId].rewardCoin;
                let addCoin = gameData.d.task[taskId].rewardAmount;
                let resultData = {};
                userModel.add(coinType, addCoin);
                resultData[coinType] = {'now': userModel.data[coinType], 'add': addCoin};
                userModel.save(function (err2, res2) {
                    if (res2 == null) {
                        cb(4);
                        return false;
                    }
                    if (resultData) {
                        msg.send(call.socket.getCid(userId), call.socket.getUuid(userId), 'globalUserChange', resultData);
                    }
                    cb(0);
                });
                taskModel.set('finish', 1);
                taskModel.save(function (err3, res3) {
                    msg.send(call.socket.getCid(userId), call.socket.getUuid(userId), 'funcTaskFinish', {'taskId': taskId});
                });
            });
        });
    },
    init: function (userId) {
        publicDao.init().table('task').pluck('taskId', 'num', 'finish')
            .wheres('userId', '=', userId).get(function (err, res) {
            if (err !== null) {
                return false;
            } else if (res.length == 0) {
                return false;
            } else {
                let data = {};
                for (let i in res) {
                    data[res[i].taskId] = {'num': res[i].num, 'finish': res[i].finish};
                }
                mem.tasks[userId] = data;
            }
        });
    },
    update: function (userId, mode, add) {
        if (!mem.tasks[userId]) {
            return false;
        }
        if (!mem.tasks[userId].length <= 0) {
            return false;
        }
        for (let taskId in mem.tasks[userId]) {
            if (gameData.d.task[taskId].mode != mode) {
                continue;
            }
            if (mem.tasks[userId][taskId].finish) {
                continue;
            }
            if (mem.tasks[userId][taskId].num >= gameData.d.task[taskId].num) {
                continue;
            }
            mem.tasks[userId][taskId].num += add;
            call.task.save(userId, taskId, mem.tasks[userId][taskId].num);
        }
    },
    save: function (userId, taskId, num) {
        let taskModel = new taskDao();
        taskModel.inTaskId(userId, taskId, function (err, res) {
            if (err || !res) {
                return false;
            }
            taskModel.set('num', num);
            taskModel.save(function () {
                msg.send(call.socket.getCid(userId), call.socket.getUuid(userId), 'globalTaskChange', {
                    'taskId': taskId,
                    'num': num
                });
            });
        });
    },
    finish: function (userId, taskId) {
        let cid = call.socket.getCid(userId);
        let uuid = call.socket.getUuid(userId);
        let taskModel = new taskDao();
        taskModel.inTaskId(userId, taskId, function (err, res) {
            if (err || !res) {
                msg.send(cid, uuid, 'error', {'api': 'funcTaskFinish', 'code': 10079});
                return false;
            }
            if (res.res.num < gameData.d.task[taskId].num) {
                msg.send(cid, uuid, 'error', {'api': 'funcTaskFinish', 'code': 10079});
                return false;
            }
            if (res.res.finish == 1) {
                msg.send(cid, uuid, 'error', {'api': 'funcTaskFinish', 'code': 10079});
                return false;
            }
            let userModel = new userDao();
            userModel.inId(userId, function (err1, res1) {
                if (res1 == null) {
                    msg.send(cid, uuid, 'error', {'api': 'funcTaskFinish', 'code': 10079});
                    return false;
                }
                let coinType = gameData.d.task[taskId].rewardCoin;
                let addCoin = gameData.d.task[taskId].rewardAmount;
                let resultData = {};
                userModel.add(coinType, addCoin);
                resultData[coinType] = {'now': userModel.data[coinType], 'add': addCoin};
                userModel.save(function (err2, res2) {
                    if (res2 == null) {
                        msg.send(cid, uuid, 'error', {'api': 'funcTaskFinish', 'code': 10079});
                        return false;
                    }
                    if (resultData) {
                        msg.send(cid, uuid, 'globalUserChange', resultData);
                    }
                });
                taskModel.set('finish', 1);
                taskModel.save(function (err3, res3) {
                    msg.send(cid, uuid, 'funcTaskFinish', {'taskId': taskId});
                });
            });
        });
    },
    clear: function (userId) {
        delete mem.tasks[userId];
    }
};
call.online = {
    logout: function (userId) {
        let timesModel = new timesDao();
        timesModel.inId(userId, function (err, res) {
            let time = (Date.now() / 1000);
            let online = time - timesModel.data.onlineTime;
            timesModel.set('online', (timesModel.data.online + online));
            timesModel.save(function () {
            });
        });
    }
};
call.auth = {
    bindGate: function (cid, serverId) {
        if (!mem.clients[cid]) {
            return false;
        }
        mem.clients[cid].serverType = 'gate';
        mem.clients[cid].serverId = serverId;
    },
    bindGame: function (cid, serverId) {
        if (!mem.clients[cid]) {
            return false;
        }
        mem.clients[cid].serverType = 'game';
        mem.clients[cid].serverId = serverId;
    },
    alertMsg: function (text) {
        for (let i in mem.clients) {
            if (mem.clients[i].serverType != 'gate') {
                continue;
            }
            msg.send(i, 1, 'alertMsg', {'text': text});
        }
    }
};

call.user = {
    list: function (page) {
        
    }
};